package chuangku

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"github.com/valyala/fasthttp"
	"kop/modules/pay/services"
	"kop/util/log"
	"strconv"
)

func Handler(ctx *fasthttp.RequestCtx) error {

	var data = struct {
		OrderId     string `json:"orderId"`
		Uid         string `json:"uid"`
		Prices      string `json:"prices"`
		ProductId   string `json:"productId"`
		ProductName string `json:"productName"`
		ChannelId   string `json:"channelId"`
		GameId      string `json:"gameId"`
		CreateTime  int    `json:"create_time"`
		Attach      string `json:"attach"`
		Sign        string `json:"sign"`
	}{}

	if err := json.Unmarshal(ctx.PostBody(), &data); err != nil {
		log.Error("json.Unmarshal(ctx.PostBody(), &data): " + err.Error())
		return err
	}

	var m = md5.New()
	m.Write([]byte(data.Uid + data.ChannelId + data.GameId + data.OrderId + data.ProductId + "334cb4d5992b450ea9171b26968930ea"))

	if hex.EncodeToString(m.Sum(nil)) != data.Sign {
		log.Error("hex.EncodeToString(m.Sum(nil)) != data.Sign")
		return errors.New("sign err")
	}

	var orderID, err = strconv.Atoi(data.Attach)
	if err != nil {
		return err
	}

	return services.Handler.CallBack(orderID)

}

type Res struct {
	Code   int    `json:"resultCode"`
	ErrMsg string `json:"errMsg"`
}

func (r *Res) Ok() string {
	r.Code = 1
	b, _ := json.Marshal(r)
	return string(b)
}

func (r *Res) Err(s string) string {
	r.Code = -1
	r.ErrMsg = s
	b, _ := json.Marshal(r)
	return string(b)
}
